package com.consul.test.service;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

@Component
@Slf4j
public class DiscoveryConsulService {

    /**
     * happen before 原则， 变量会先完成初始化，然后才是当前的类实例干初始化的工作
     */
    @Resource
    private DiscoveryClient discoveryClient;


    /**
     * test discovery service
     */
    public void getTestConsulService() {
        List<String> services = discoveryClient.getServices();
        List<ServiceInstance> serviceInstanceList = discoveryClient.getInstances("test-consul");
        if (serviceInstanceList != null && serviceInstanceList.size() != 0) {
            ServiceInstance serviceInstance = serviceInstanceList.get(0);
            log.info("service :{} ", serviceInstance.toString());
            //	Older versions of Spring Cloud Consul populated the ServiceInstance.getMetadata() method from Spring Cloud Commons by parsing the spring.cloud.consul.discovery.tags property. This is no longer supported, please migrate to using the spring.cloud.consul.discovery.metadata map. so application.yml set tags: key=value
            Map<String, String> serviceInstanceMetadata = serviceInstance.getMetadata();
            log.info("{}", serviceInstanceMetadata);
        }

    }
}
